package com.lry.it;

import com.lry.block.Block;
import com.lry.table.Table;
import com.lry.util.Slice;

import java.util.Map;

public final class TableIterator extends AbstractSeekingIterator<Slice,Slice>{

    private final Table table;

    private final BlockIterator blockIterator;//index block的迭代器

    private BlockIterator current;//data block的迭代器

    public TableIterator(Table table, BlockIterator blockIterator)
    {
        this.table = table;
        this.blockIterator = blockIterator;
        current = null;
    }


    @Override
    protected void seekToFirstInternal() {
        blockIterator.seekToFirst();
        current = null;
    }

    @Override
    protected void seekInternal(Slice targetKey) {
        blockIterator.seek(targetKey);
        if (blockIterator.hasNext()) {
            current = getNextBlock();
            current.seek(targetKey);
        }else{
            current = null;
        }

    }

    private BlockIterator getNextBlock() {
        Slice blockHandle = blockIterator.next().getValue();
        Block dataBlock = table.openBlock(blockHandle);
        return dataBlock.iterator();
    }

    @Override
    protected Map.Entry<Slice, Slice> getNextElement() {
        boolean currentHasNext = false;
        while (true) {
            if (current != null) {
                currentHasNext = current.hasNext();
            }
            if (!(currentHasNext)) {
                if (blockIterator.hasNext()) {
                    current = getNextBlock();
                }
                else {
                    break;
                }
            }
            else {
                break;
            }
        }
        if (currentHasNext) {
            return current.next();
        }
        else {
            // set current to empty iterator to avoid extra calls to user iterators
            current = null;
            return null;
        }
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("ConcatenatingIterator");
        sb.append("{blockIterator=").append(blockIterator);
        sb.append(", current=").append(current);
        sb.append('}');
        return sb.toString();
    }
}
